package com.jxm.security.controller;

import com.jxm.security.common.R;
import com.jxm.security.entity.User;
import com.jxm.security.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2022/5/24 21:04
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    LoginService loginService;

    @GetMapping("/test")
    @PreAuthorize("hasAuthority('user.list')")
    public String test(){
        return "security";
    }

    //登录
    @PostMapping("/login")
    public R login(@RequestBody User user){
       return loginService.login(user);
    }

    //登出
    @GetMapping("/logout")
    public String logout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User loginUser = (User) authentication.getPrincipal();
        String id = loginUser.getId();
        //从redis移除用户
        redisTemplate.delete("login"+id);
        return R.ok().getMessage();
    }
}
